package com.liangtian.mdm.system.file.service.impl;

import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.jsp.common.JspUtil;
import com.liangtian.mdm.system.file.dao.SysFileUpdateDao;
import com.liangtian.mdm.system.file.model.SysFileUpdate;
import com.liangtian.mdm.system.file.service.SysFileUpdateService;
import com.liangtian.mdm.system.parameter.service.SysParameterService;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
import java.util.Map.Entry;

@Service
public class SysFileUpdateServiceImpl implements SysFileUpdateService {

    @Autowired
    SysFileUpdateDao sysFileUpdateDao;

    @Autowired
    private SysParameterService sysParameterService;

    //@Value("${ConstantBean.CURRENT_SESSION_USER}")
    //private String ConstantBean.CURRENT_SESSION_USER;

    @Override
    public Map<String, Object> insertFileUpdate(HttpServletRequest request, Map<String, Object> Fcond) {
        Map<String, Object> resMap = new HashMap<>();
        boolean success = true;
        /*		StringBuffer fileName=new StringBuffer();
         */
        List<String> fileNameLst = new ArrayList<String>();
        try {
            String surveyType = (String) Fcond.get("surveyType"); //方便测试，后期从页面获取所属业务
//			String surveyName=(String)Fcond.get("surveyName");
            String dataId = (String) Fcond.get("dataId");
            String updateId = (String) Fcond.get("updateId");
            String operType = (String) Fcond.get("operType");
            /*			List<String> fileList = (List<String>)Fcond.get("fileList");*/
            String systemCode = sysParameterService.getSysParamValue("systemCode", "");// 获取系统参数filePath，如果返回值为空则默认返回值为"C:/mdmFile"
            //String filePath="C:/mdmFile"; //文件存储路径，后期需要从系统参数中获取
            String filePath = "";//JspUtil.getFilePath();
//			String filePath = sysParameterService.getSysParamValue("");
            if ("WanDa".equals(systemCode)) {
                filePath = JspUtil.getFilePath();
            } else {
                filePath = sysParameterService.getSysParamValue("filePath", "C:/mdmFile");
            }
//			System.out.println(filePath);
            //创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //判断 request 是否有文件上传,即多部分请求
            if (multipartResolver.isMultipart(request)) {
                //转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //取得request中的所有文件名
                MultiValueMap<String, MultipartFile> map = multiRequest.getMultiFileMap();
                Set<Entry<String, List<MultipartFile>>> mapSet = map.entrySet();
                String keyColumn = null;//附件的列名,如:c_001,c_002
                int count = 0;
                for (Entry<String, List<MultipartFile>> entry : mapSet) {
                    keyColumn = entry.getKey();
                    count = charCount(keyColumn, '_');
                    if (2 == count)
                        keyColumn = keyColumn.substring(0, keyColumn.lastIndexOf("_"));
                    //记录上传过程起始时的时间，用来计算上传时间
                    int pre = (int) System.currentTimeMillis();
                    //取得上传文件
                    MultipartFile file = entry.getValue().get(0);

                    if (file != null) {
                        //取得当前上传文件的文件名称
                        String myFileName = file.getOriginalFilename();
                        /* fileName.append(myFileName).append(",");*/
                        //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                        if (myFileName.trim() != "") {
                            fileNameLst.add(myFileName);
                            System.out.println(myFileName);
                            //定义上传路径
                            String path = filePath + "/" + surveyType + "/" + new Date().getTime() + "/" + myFileName;
                            //创建目标文件夹
                            (new File(path)).mkdirs();
                            File localFile = new File(path);
                            file.transferTo(localFile);
                            this.insertFileUpdateInfo(myFileName, path, file.getSize(), surveyType, dataId, keyColumn, operType, updateId);
                        }
                    }
                    //记录上传该文件后的时间
                    int finaltime = (int) System.currentTimeMillis();
                    System.out.println(finaltime - pre);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }
        resMap.put("IsSuccess", success);
        resMap.put("FileNameLst", fileNameLst);
        return resMap;
    }

    private Integer charCount(String key, char c) {
        char[] chars = key.toCharArray();
        int count = 0;
        for (int i = 0; i < chars.length; i++) {
            if (c == chars[i])
                count++;
        }
        return count;
    }

    /**
     * 插入附件信息
     *
     * @param fileName
     * @param path
     * @param fileSize
     * @param surveyType
     */
    private void insertFileUpdateInfo(String fileName, String path, long fileSize, String surveyType, String dataId, String keyColumn, String operType, String updateId) {
        //获取列名
        SysFileUpdate sysFileUpdate = new SysFileUpdate();
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        sysFileUpdate.setCreator(String.valueOf(user.getUserId()));
        sysFileUpdate.setFileName(fileName);
        sysFileUpdate.setFileType(fileName.substring(fileName.lastIndexOf(".")));
        sysFileUpdate.setFilePath(path);
        sysFileUpdate.setFileSize(fileSize + "");
        sysFileUpdate.setSurveyType(surveyType);
        sysFileUpdate.setDataId(dataId);
        sysFileUpdate.setFileColumn(keyColumn);//--把列名保存进去
        sysFileUpdate.setOperType(operType);
        sysFileUpdate.setUpdateId(updateId);
        sysFileUpdateDao.insertSysFileUpdate(sysFileUpdate);
    }

    @Override
    public List<SysFileUpdate> queryFileUpdateBySurvey(Map<String, Object> param) {
        return sysFileUpdateDao.queryFileUpdateBySurvey(param);
    }

    @Override
    public SysFileUpdate queryFileUpdateById(String id) {
        return sysFileUpdateDao.queryFileUpdateById(id);
    }


    @Override
    public void delFileUpdateByPath(SysFileUpdate sFileUpdate) {
        String filePath = sFileUpdate.getFilePath().substring(0, sFileUpdate.getFilePath().lastIndexOf("/"));
        File file = new File(filePath);
        if (file.exists()) {
            deleteFileUpdate(file);//删除文件夹下的文件
        }
        sysFileUpdateDao.delFileUpdate(sFileUpdate.getId());//删除附件表的信息
    }


    @Override
    public void delFileUpdateByPath(List<SysFileUpdate> sFileUpdates) {
        for (int i = 0; i < sFileUpdates.size(); i++) {
            SysFileUpdate sysFileUpdate = sFileUpdates.get(i);
            //String filePath=sysFileUpdate.getFilePath().substring(0, sysFileUpdate.getFilePath().lastIndexOf("/"));
            String filePath = sysFileUpdate.getFilePath();//只删除目标文件
            File file = new File(filePath);
            if (file.exists()) {
                deleteFileUpdate(file);//删除文件夹下的文件
            }
            sysFileUpdateDao.delFileUpdate(sysFileUpdate.getId());//删除附件表的信息
        }


    }

    /**
     * 递归循环删除文件夹下面的目录及文件
     *
     * @param file
     */
    private static void deleteFileUpdate(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteFileUpdate(files[i]);
            }
        }
        file.delete();
    }


    @Override
    public List<SysFileUpdate> queryFileUpdateByCond(Map<String, Object> cond) {
        return sysFileUpdateDao.queryFileUpdateByCond(cond);
    }

    @Override
    public List<SysFileUpdate> queryFileUpdatesBySurvey(Map<String, Object> param) {
        return sysFileUpdateDao.queryFileUpdatesBySurvey(param);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> insertSysContentFileUpdate(HttpServletRequest request, Map<String, Object> Fcond) {
        Map<String, Object> resMap = new HashMap<>();
        boolean success = true;
        List<String> fileNameLst = new ArrayList<String>();
        try {
            String surveyType = (String) Fcond.get("surveyType"); //方便测试，后期从页面获取所属业务
            String surveyName = (String) Fcond.get("surveyName");
            String dataId = (String) Fcond.get("dataId");
            String updateId = (String) Fcond.get("updateId");
            String operType = (String) Fcond.get("operType");
            List<String> fileList = (List<String>) Fcond.get("fileList");
            String filePath = "C:/mdmFile"; //文件存储路径，后期需要从系统参数中获取

            //创建一个通用的多部分解析器
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            //判断 request 是否有文件上传,即多部分请求
            if (multipartResolver.isMultipart(request)) {
                //转换成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                //取得request中的所有文件名
                MultiValueMap<String, MultipartFile> map = multiRequest.getMultiFileMap();
                Set<Entry<String, List<MultipartFile>>> mapSet = map.entrySet();
                for (Entry<String, List<MultipartFile>> entry : mapSet) {
                    //记录上传过程起始时的时间，用来计算上传时间
                    int pre = (int) System.currentTimeMillis();
                    //取得上传文件
                    MultipartFile file = entry.getValue().get(0);
                    if (file != null) {
                        //取得当前上传文件的文件名称
                        String myFileName = file.getOriginalFilename();
                        String keyColumn = fileList.get(0).trim();//赋值的是版本号
                        /* fileName.append(myFileName).append(",");*/
                        //如果名称不为“”,说明该文件存在，否则说明该文件不存在
                        if (myFileName.trim() != "") {
                            fileNameLst.add(myFileName);
                            //System.out.println(myFileName);
                            //定义上传路径
                            String path = filePath + "/" + surveyName + "/" + new Date().getTime() + "/" + myFileName;
                            //创建目标文件夹
                            (new File(path)).mkdirs();
                            File localFile = new File(path);
                            file.transferTo(localFile);
                            this.insertFileUpdateInfo(myFileName, path, file.getSize(), surveyType, dataId, keyColumn, operType, updateId);
                        }
                    }
                    //记录上传该文件后的时间
                    int finaltime = (int) System.currentTimeMillis();
                    System.out.println(finaltime - pre);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            success = false;
        }
        resMap.put("IsSuccess", success);
        resMap.put("FileNameLst", fileNameLst);
        return resMap;
    }

}
